package com.example.schoolblog.blog.Controller;


import com.example.schoolblog.blog.Dto.CommentCreateDto;
import com.example.schoolblog.blog.Dto.CommentDto;
import com.example.schoolblog.blog.Dto.ResultDTO;
import com.example.schoolblog.blog.Enums.CommentTypeEnum;
import com.example.schoolblog.blog.Exception.CustomizeErrorCode;
import com.example.schoolblog.blog.Model.Comment;
import com.example.schoolblog.blog.Model.User;
import com.example.schoolblog.blog.Service.CommentServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class CommentController {

    @Autowired
    private CommentServer commentServer;

    @ResponseBody
    @RequestMapping(value = "/comment",method = RequestMethod.POST)
    public Object post(@RequestBody CommentCreateDto commentCreateDto,
                       HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        if(user == null){
            return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
        }
        if(commentCreateDto == null || StringUtils.isBlank(commentCreateDto.getContent())){
            return ResultDTO.errorOf(CustomizeErrorCode.COMMENT_IS_EMPTY);
        }
        Comment comment = new Comment();
        comment.setParentId(commentCreateDto.getParentId());
        comment.setContent(commentCreateDto.getContent());
        comment.setType(commentCreateDto.getType());
        comment.setGmtCreate(System.currentTimeMillis());
        comment.setGmtModified(comment.getGmtCreate());
        comment.setCommentator(user.getId());
        commentServer.insert(comment,user);
        return ResultDTO.okOf();
    }

    //查询问题的评论列表以及评论的回复列表
    @ResponseBody
    @RequestMapping(value = "/comment/{id}",method = RequestMethod.GET)
    public ResultDTO<List<CommentDto>> comments(@PathVariable(name ="id") Long id){
        List<CommentDto> commentDtos = commentServer.listByTargetId(id, CommentTypeEnum.COMMENT);
        return ResultDTO.okOf(commentDtos);
    }

}
